package com.asuka.eva.config;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author Jin zuo wei
 * @version 1.0.0
 * @description spring-ThreadPoolTaskExecutor:简单配置文件
 * @since 2021/12/26
 */
@Configuration
@Slf4j
public class ThreadPoolConfig {
    // 核心线程 - 最少存在10个线程处理数据
    private static final int corePoolSize = 2;
    // 最大线程 - 若达到最大队列后若总线程小于最大线程则创建线程
    private static final int maxPoolSize = 2;
    // 队列线程 - 若核心线程已满，则进入队列进行等待
    private static final int queueCapacity = 10;
    // 线程活跃时间（秒）- 待确认
    private static final int keepAliveTime = 60;
    // 线程前缀
    private static final String threadNamePrefix = "taskThread-";

    @Bean
    public ThreadPoolTaskExecutor commonThreadPoolExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(corePoolSize);
        executor.setMaxPoolSize(maxPoolSize);
        executor.setQueueCapacity(queueCapacity);
        executor.setKeepAliveSeconds(keepAliveTime);
        executor.setThreadNamePrefix(threadNamePrefix);
        // 此处设置拒绝策略，当队列满，且已经达到MaxPoolSize则进入拒绝策略。具体百度。
        // CallerRunsPolicy 让调用者线程执行被拒绝的任务
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.setWaitForTasksToCompleteOnShutdown(true);
        executor.initialize();
        log.info("TaskThreadPool initialization completed.");
        return executor;
    }
}
